<template>
  <el-dialog
      v-model="openDialog"
      :title="dialogTitle"
      :width="800"
      :before-close="handleClose"
  >
    <div class="new-dialogDiv">
      <!--计算结果展示窗口-->
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="统计图" name="first">
          <div id="resultChartDiv" style="width:100%;height:400px;"></div>
        </el-tab-pane>
        <el-tab-pane label="表格" name="second">
          <el-table v-loading="loading" ref="tableRef" :data="dataList" stripe
                    row-key="versionCode">
            <el-table-column :label="valueTypeLabel" align="center" prop="valueType" />
            <el-table-column label="滑坡面积（km²）" align="center" prop="slopeArea" />
            <el-table-column label="滑坡面密度（%）" align="center" prop="slopeDensity" />
          </el-table>
          <div style="text-align: center;margin-top: 15px;">
            <el-button type="primary" @click="handleExport">导出</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </el-dialog>
</template>

<script setup>
import * as echarts from "echarts";
import { exportByDspIdAndType } from "@/api/slideAssess/distributionPatternAnalysis/indexMap";

const { proxy } = getCurrentInstance();
const props = defineProps(['open','result']);
const emits = defineEmits(['closeResultDialog'])
const loading = ref(false);

//是否显示计算结果弹窗
const openDialog = ref(false);
//计算结果弹窗标题
const dialogTitle = ref("");
//计算结果弹窗tab选择
const activeName = ref('first');
//计算结果数据列表
const dataList= ref([]);
//计算结果分段名称
const valueTypeLabel = ref("");
//计算结果图例列表
const legendList = ref([]);
//统计图
const resultChart = ref(null);

//是否显示
const isOpen = watch(() => props.open, value => {// watch函数监听props.open
  openDialog.value = value;
},{immediate:true});

const handleClose = () => {
  openDialog.value = false;
  emits('closeResultDialog', true);
}

const handleClick = (tab, event) => {
  console.log(tab, event)
}

//获取计算结果分段名称
function getValueTypeLabel(value){
  dialogTitle.value = value + "统计结果";
  let label = "";
  if(value=="与地震烈度的关系"){
    label = "地震烈度";
  }else if(value=="与距断层距离的关系"){
    label = "距断层距离（km）";
  }else if(value=="与高程的关系"){
    label = "海拔高程（km）";
  }else if(value=="与地形坡度的关系"){
    label = "地形坡度（°）";
  }else if(value=="与坡向的关系"){
    label = "坡向";
  }else if(value=="与水系的关系"){
    label = "距水系距离";
  }else if(value=="与地层岩性的关系"){
    label = "地层岩性";
  }
  valueTypeLabel.value = label;
}

//获取计算结果表格数据列表
function getResultDataList(type,resultDataList,resultLegendList){
  console.log("获取计算结果表格数据列表");
  console.log(type);
  console.log(resultDataList);
  console.log(resultLegendList);
  if(type && resultDataList && resultLegendList){
    let list = [];
    console.log(resultDataList.length);
    for(let i=0;i<resultDataList.length;i++){
      let obj = resultDataList[i];
      let slopeArea = obj.slopeArea;
      let slopeDensity = obj.slopeDensity;
      //获取分段名称
      let valueType = "";
      let val = "";
      if(type=="与地震烈度的关系"){
        val = obj.intensity;//烈度。5Ⅴ、6 Ⅵ、7 Ⅶ、8 Ⅷ、9 Ⅸ、10 Ⅹ、11 Ⅺ、12 Ⅻ
      }else if(type=="与距断层距离的关系"){
        val = obj.faultRange;//距断层的距离。7,>30;6,25~30;5,20~25;4,15~20;3,10~15;2,5~10;1,0~5
      }else if(type=="与高程的关系"){
        val = obj.teraRange;//高程。1,<0.6;2,0.6~1;3,1~1.5;4,1.5~2;5,2~2.5;6,2.5~3;7,3~3.5;8,>3.5
      }else if(type=="与地形坡度的关系"){
        val = obj.slopeRange;//坡度。1,<15;2,15~25;3,25~35;4,35~45;5,45~55;6,>55
      }else if(type=="与坡向的关系"){
        val = obj.aspectRange;//坡向1,N;2,NE;3,E;4,ES;5,S;6,SW;7,W;8,WN
      }else if(type=="与水系的关系"){
        val = obj.drainageRange;//距水系距离。1,0~500;2,500~1000;3,1000~1500;4,1500~2000;5,>2000
      }else if(type=="与地层岩性的关系"){
        val = obj.lithologyRange;//地层岩性。1,Q4;2,Er;3,T3z;4,T3zh;5,T2zg;6,T1b;7,Tγo;8,P2b-d;9,Psd-d;10,C2h;11,Cz-h;12,D2y
      }
      if(val && resultLegendList && resultLegendList.length>0){
        for(let i=0;i<resultLegendList.length;i++){
          if(resultLegendList[i].value==val){
            valueType = resultLegendList[i].name;//分段名称
            break;
          }
        }
      }
      let tempObj = {
        valueType:valueType,
        slopeArea:slopeArea,
        slopeDensity:slopeDensity
      }
      list.push(tempObj);
    }
    dataList.value = list;
    console.log("计算结果数据列表表格");
    console.log(list);
  }
}

//表格导出Excel
function handleExport(){
  let dspId = props.result.dspId;
  let type = props.result.type;//1-7
  proxy.download("/lawAnalysis/exportByDspIdAndType", {
    dspId:dspId,type:type
  }, `表格_${new Date().getTime()}.xlsx`);
  /*exportByDspIdAndType(dspId,type).then(response => {
    console.log("表格导出Excel");
    console.log(response);
  }).catch(() => {
    // proxy.$modal.msgError("导出失败");
  });*/
}

//获取统计图
function getResultChart(){
  let list = dataList.value;//计算结果数据列表表格
  if(list!=null && list.length>0 && document.getElementById('resultChartDiv')) {
    if(resultChart.value){
      resultChart.value.dispose();//移除
    }
    //初始化
    resultChart.value = echarts.init(document.getElementById('resultChartDiv'));

    //分段名称数组
    let xDataArray = [];
    for(let i=0;i<list.length;i++){
      xDataArray.push(list[i].valueType);
    }

    //滑坡面密度（%）数组
    let yDataArray1 = [];
    for(let i=0;i<list.length;i++){
      yDataArray1.push(list[i].slopeDensity);
    }

    //滑坡面积（km²）数组
    let yDataArray2 = [];
    for(let i=0;i<list.length;i++){
      yDataArray2.push(list[i].slopeArea);
    }

    // 指定图表的配置项和数据
    let option = {
      color: ['rgba(50, 229, 255, 1)', 'rgba(250, 207, 18, 1)'],
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999'
          }
        }
      },
      grid: {
        top: '30%',
        left: '10%',
        right: '10%',
        bottom: '20%',
        containLabel: true
      },
      toolbox:{
        feature:{
          saveAsImage:{}
        }
      },
      xAxis: [
        {
          type: 'category',
          data: xDataArray,
          axisLine: {
            show: true,
            lineStyle: {
              color: '#7B68EE'
            }
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: 'blue',
              width: 1,
              type: 'solid'
            }
          },
          axisPointer: {
            type: 'shadow'
          },
        }
      ],
      yAxis: [
        {
          type: 'value',
          name: `                {legend|}  {value|滑坡面密度（%）}`,
          axisLabel: {
            color: '#FF6347'
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#FFDEAD'
            }
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: 'blue',
              width: 1,
              type: 'solid'
            }
          },
          nameTextStyle: {
            rich: {
              legend: {
                width: 12,
                height: 4,
                backgroundColor: '#EE82EE'
              },
              value: {
                color: '#FF8C00'
              }
            }
          }
        },
        {
          type: 'value',
          name: `{legend|}  {value|滑坡面积（km²）}           `,
          axisLabel: {
            color: '#00BFFF'
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#66CDAA'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#E6E6FA',
              width: 1,
              type: 'solid'
            }
          },
          nameTextStyle: {
            rich: {
              legend: {
                width: 12,
                height: 4,
                backgroundColor: '#87CEFA'
              },
              value: {
                color: '#CD853F'
              }
            }
          }
        }
      ],
      series: [
        {
          name: '滑坡面密度（%）',
          type: 'bar',
          data: yDataArray1,
          barWidth: 14, // 柱状图的宽度
          itemStyle: {
            borderRadius: 8,
            color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
              { offset: 0, color: 'rgba(50, 229, 255, 1)' },
              { offset: 1, color: 'rgba(50, 229, 255, 0.8)' }
            ])
          }
        },
        {
          name: '滑坡面积（km²）',
          type: 'line',
          yAxisIndex: 1,
          data: yDataArray2,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
              {
                offset: 0,
                color: 'rgba(183, 75, 238)'
              },
              {
                offset: 1,
                color: 'rgba(250, 207, 18)'
              }
            ])
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
              {
                offset: 0,
                color: 'rgba(183, 75, 238,0.2)'
              },
              {
                offset: 1,
                color: 'rgba(250, 207, 18)'
              }
            ])
          },
          showSymbol: false
        }
      ]
    };

    // 使用刚指定的配置项和数据显示图表。 给一个延时
    resultChart.value.clear();
    option && resultChart.value.setOption(option);
  }
}

//获取计算结果
const getResult = watch(() => props.result, value => {// watch函数监听props.result
  if(value){
    let resultDialogType = value.resultDialogType;
    if(resultDialogType){
      //获取计算结果分段名称
      getValueTypeLabel(resultDialogType);
      let resultLegendList = value.resultLegendList;//计算结果图例列表
      if(resultLegendList){
        legendList.value = resultLegendList;
        let resultDataList = value.resultDataList;//计算结果数据列表
        if(resultDataList){
          //获取计算结果表格数据列表
          getResultDataList(resultDialogType,resultDataList,resultLegendList);
          nextTick(() => {
            //获取统计图
            getResultChart();
          });
        }
      }
    }
  }

},{immediate:true});

onMounted(() => {
  //获取统计图
  // getResultChart();
})
</script>

<style scoped lang="scss">
.new-dialogDiv {
  padding:20px;
}

</style>